/**
 * 获取缓存中用于请求的key
 */
var getStorageKey = function() {
	var key = getApp().globalData.key || null;
	return key;
}
/**
 * 验证是否授权登录过
 * 将当前页面的参数载入缓存,并跳转至授权登录页面
 */
var verifyAuth = function(callback, redirectToHome = false) {
	var phone = uni.getStorageSync('phone') || null;
	if (getStorageKey() && phone) {
		callback();
		return;
	}
	uni.showModal({
		title: '授权登陆',
		content: '为了为您提供相关服务，推荐您授权信息后查看',
		success: function(res) {
			if (res.confirm) {
				var pages = getCurrentPages() //获取加载的页面
				var currentPage = pages[pages.length - 1] //获取当前页面的对象
				var url = currentPage.route //当前页面url
				var options = currentPage.options //如果要获取url中所带的参数可以查看options
				var param = '';
				var index = 0;
				for (var key in options) {
					if (index == 0) {
						var and = '?';
					} else {
						var and = '&';
					}
					param += and + key + '=' + options[key];
					++index;
				}
				var path = '/' + url + param;
				uni.setStorage({
					key: 'path',
					data: path,
					success: function() {
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}
				})
			} else {
				if (redirectToHome) {
					uni.switchTab({
						url: '/pages/store/home/home'
					})
				}
			}
		}
	})
}
var share = function(path = null) {
	if (!path) {
		var pages = getCurrentPages() //获取加载的页面
		var currentPage = pages[pages.length - 1] //获取当前页面的对象
		var url = currentPage.route //当前页面url
		var options = currentPage.options //如果要获取url中所带的参数可以查看options
		var param = '';
		for (var key in options) {
			param += '&' + key + '=' + options[key]
		}
		path = '/' + url + "?scene=0" + param;
	}
	var redirect = '/pages/index/index?redirect=' + escape(path);
	// unecape()
	console.log('redirect', redirect)
	return {
		path: redirect
	}
}
/**
 * 分页加载提示
 */
var getPageConfig = function() {
	return {
		current_page: 1,
		loading_msg: '加载中……',
		finish_msg: '已展示全部',
		empty_msg: '什么都没找到',
		show_loading: false,
		show_finish: false,
		show_empty: false,
	}
}

/**
 * get参数转json对象
 */
var urlFormatToJson = function(url) {
	var param = {};
	url.replace(/([^?&]+)=([^?&]+)/g, function(s, v, k) {
		param[v] = decodeURIComponent(k);
		return k + '=' + v;
	});
	return param;
}


export default {
	getStorageKey,
	verifyAuth,
	share,
	getPageConfig,
	urlFormatToJson,
}
